import jsApi from './cx580.jsApi';
import common from './common';
import {Modal} from 'antd-mobile'

let g_userContainer = undefined;

let g_userId = ''; //CXY_3FBA032214714C19BA4CCA267F86C550
let g_userToken = ''; //60EB65A06DD3471C7B769091A9F70CBE
let g_city = '';
let g_lng = '';
let g_lat = '';
let g_openId = '';
let g_deviceId = '';
let g_userType = 'App';

/**
 * 用户帮助类
 */
class UserHelper {
    //userContainer = "";
    // userId = "";
    // userToken = "";
    //city = "";


    constructor() {
        this._initialize();
    }

    _initialize() {
        // setTimeout(() => {
        //     this._getContainer();
        // }, 500);
        if (common.isCXYApp()) {
            //执行到这里，说明是在 app 中运行
            g_userContainer = "App";
            this._getUserInfoFromApp();
            // setTimeout(() => {
            //     this._getUserInfoFromApp();
            // }, 150);
        } else {
            //执行到这里，说明不在 app 中运行
            g_userContainer = "";

            //alert("请使用车行易APP访问！");
        }
    }

    _getContainer() {
        try {
            jsApi.call({
                "commandId": "",
                "command": "netstat"
            }, (data) => {
                //执行到这里，说明是在 app 中运行
                g_userContainer = "App";
                this._getUserInfoFromApp();
            });
        } catch (error) {
            //执行到这里，说明不在 app 中运行
            g_userContainer = "";
        }
    }


    /**
     * 从 app 中获取用户 token
     */
    _getUserInfoFromApp(callBack) {
        try {
            jsApi.call({
                "commandId": "",
                "command": "getSymbol",
                "data": {
                    "userid": "",
                    "lng": "",
                    "lat": "",
                    "version": "",
                    "channel": "",
                    "cars": "",
                    "phone": "",
                    "name": "",
                    "type|orderNum": "",
                    "city": "",
                    "accountId": "",
                    "token": "",
                    "carId": "",
                    "carNumber": ""
                }
            }, (data) => {
                g_userId = data.data.accountId;
                g_userToken = data.data.token;
                g_city = data.data.city;
                g_lat = data.data.lat;
                g_lng = data.data.lng;
                g_deviceId = data.data.userid;
                if (data.data.accountId) {
                    sessionStorage.setItem("userId", g_userId);
                    sessionStorage.setItem("token", g_userToken);
                    sessionStorage.setItem("userType", g_userType);
                    sessionStorage.setItem("deviceId", g_deviceId);
                }
                callBack && callBack({
                    userId: g_userId,
                    token: g_userToken,
                    city: g_city,
	                  deviceId :g_deviceId,
                    userType: g_userType
                });
            });
        } catch (error) {
            //执行到这里，说明不在 app 中运行
            // alert("调试信息：调用APP JS SDK出错了 获取APP信息出错了");
        }
    }

    /**
     * app 登陆
     */
    _appLogin(callback, cancelCallBack) {
        jsApi.call({
            "commandId": "",
            "command": "login"
        }, (data) => {
            localStorage.setItem("upLoginState", "1"); //用户登录状态发生变化
            if (data.data.accountId) {
                g_userId = data.data.accountId;
                this._getUserInfoFromApp();
                if (callback) {
                    callback();
                }
            }
            else {
                cancelCallBack && cancelCallBack();
            }
        });
    }

    /**
     * 获取 userId 和 token
     */
    getUserIdAndToken() {
        if (g_userContainer == "App") {
            this._getUserInfoFromApp();
        } else {
            //非APP时，直接返回缓存中的userId 和 token
            g_userId = sessionStorage.getItem("userId");
            g_userToken = sessionStorage.getItem("token");
            g_userType = sessionStorage.getItem("userType");
            g_lat = sessionStorage.getItem('lat');
            g_lng = sessionStorage.getItem('lng');
            g_openId = sessionStorage.getItem('openId');
        }
        return {
            userId: g_userId,
            token: g_userToken,
            city: g_city,
            userType: g_userType,
            lng: g_lng,
            lat: g_lat,
            openId: g_openId,
            detailUserType:localStorage.getItem('detailUserType'),
        }
    }

    getUserIdAndTokenWithCallBack(resultCallBack) {
        if (g_userContainer == "App") {
            this._getUserInfoFromApp(resultCallBack);
        } else {
            //非APP时，直接返回缓存中的userId 和 token
            g_userId = sessionStorage.getItem("userId");
            g_userToken = sessionStorage.getItem("token");
            g_userType = sessionStorage.getItem("userType");
            resultCallBack({
                userId: g_userId,
                token: g_userToken,
                city: g_city,
                userType: g_userType
            })
        }
    }


    /**
     * 登陆
     * @param callback function 登陆成功之后的回调
     */
    Login(callback, cancelCallBack) {
        //避免弹出多个提示框，这里先清除上一个提示框
        let div = document.querySelector(".am-modal-wrap");
        if (div) {
            div = div.parentNode;
            if (div) {
                div.parentNode.removeChild(div);
            }
        }

        Modal.alert('', '此操作需要登录才能完成', [
            {
                text: '登录', onPress: () => {
                if (g_userContainer == "App") {
                    setTimeout(()=>{
	                    this._appLogin(callback, cancelCallBack)
                    },100); ///防止去登陆页，点击返回看到登陆提示弹框
                } else {
                    alert("Login no app")
                }
            }, style: {color: '#108ee9'}
            },
            {
                text: '取消', onPress: () => {
                //不用关闭页面
                //cancelCallBack && cancelCallBack();
            }, style: {color: '#108ee9'}
            },
        ])
    }
}
;

// 实例化后再导出
export default new UserHelper()